import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { JSATemplate, JSATemplateForm, JSAWorkStep, JSAHazard, JSAControlMeasure } from '@/types'

export const useJSATemplateStore = defineStore('jsaTemplate', () => {
  const templates = ref<JSATemplate[]>([
    {
      id: 1,
      name: '高空作业模板',
      jobType: '高空作业',
      workSteps: [
        { id: 1, stepName: '作业准备', sequence: 1 },
        { id: 2, stepName: '安装调试作业', sequence: 2 },
        { id: 3, stepName: '作业完毕', sequence: 3 }
      ],
      hazards: [
        { id: 1, hazardName: '作业环境不明及身体状态不行易发生事故' },
        { id: 2, hazardName: '安全用具、防护用品、监护不足易发生事故' },
        { id: 3, hazardName: '作业过程中工具脱手导致高处落物' },
        { id: 4, hazardName: '作业过程中突发身体不适或中暑' },
        { id: 5, hazardName: '工具、物料、或墙上结构件受撞脱落' }
      ],
      controlMeasures: [
        { id: 1, measureName: '高空作业前必须进行过入厂安全教育' },
        { id: 2, measureName: '作业前仔细检查所配备的安全设施、用具牢固可靠,穿戴好合适的PPE' },
        { id: 3, measureName: '作业前检查登高车各项功能,确认正常后方可作业' },
        { id: 4, measureName: '禁止抛接物品、材料工具等,工具必须放在工具包里' },
        { id: 5, measureName: '不得跨站登高车和支撑结构之间' },
        { id: 6, measureName: '作业区域使用警示带进行隔离,无关人员禁止入内' },
        { id: 7, measureName: '作业过程中合理安排休息时间,注意提醒作业人员饮水' },
        { id: 8, measureName: '人员如有不适情况,立即停止作业,至阴凉通风处休息' },
        { id: 9, measureName: '登高车下降前,梳理登高车平台上的物料和工具' },
        { id: 10, measureName: '下降前,看护人员注意查看登高车附近的物料等' }
      ],
      workStepHazards: [
        { id: 1, workStepId: 1, hazardId: 1, workStep: { id: 1, stepName: '作业准备', sequence: 1 }, hazard: { id: 1, hazardName: '作业环境不明及身体状态不行易发生事故' } },
        { id: 2, workStepId: 1, hazardId: 2, workStep: { id: 1, stepName: '作业准备', sequence: 1 }, hazard: { id: 2, hazardName: '安全用具、防护用品、监护不足易发生事故' } },
        { id: 3, workStepId: 2, hazardId: 3, workStep: { id: 2, stepName: '安装调试作业', sequence: 2 }, hazard: { id: 3, hazardName: '作业过程中工具脱手导致高处落物' } },
        { id: 4, workStepId: 2, hazardId: 4, workStep: { id: 2, stepName: '安装调试作业', sequence: 2 }, hazard: { id: 4, hazardName: '作业过程中突发身体不适或中暑' } },
        { id: 5, workStepId: 2, hazardId: 5, workStep: { id: 2, stepName: '安装调试作业', sequence: 2 }, hazard: { id: 5, hazardName: '工具、物料、或墙上结构件受撞脱落' } },
        { id: 6, workStepId: 3, hazardId: 3, workStep: { id: 3, stepName: '作业完毕', sequence: 3 }, hazard: { id: 3, hazardName: '作业过程中工具脱手导致高处落物' } },
        { id: 7, workStepId: 3, hazardId: 5, workStep: { id: 3, stepName: '作业完毕', sequence: 3 }, hazard: { id: 5, hazardName: '工具、物料、或墙上结构件受撞脱落' } }
      ],
      hazardControls: [
        { id: 1, hazardId: 1, controlMeasureId: 1, hazard: { id: 1, hazardName: '作业环境不明及身体状态不行易发生事故' }, controlMeasure: { id: 1, measureName: '高空作业前必须进行过入厂安全教育' } },
        { id: 2, hazardId: 2, controlMeasureId: 2, hazard: { id: 2, hazardName: '安全用具、防护用品、监护不足易发生事故' }, controlMeasure: { id: 2, measureName: '作业前仔细检查所配备的安全设施、用具牢固可靠,穿戴好合适的PPE' } },
        { id: 3, hazardId: 2, controlMeasureId: 3, hazard: { id: 2, hazardName: '安全用具、防护用品、监护不足易发生事故' }, controlMeasure: { id: 3, measureName: '作业前检查登高车各项功能,确认正常后方可作业' } },
        { id: 4, hazardId: 3, controlMeasureId: 4, hazard: { id: 3, hazardName: '作业过程中工具脱手导致高处落物' }, controlMeasure: { id: 4, measureName: '禁止抛接物品、材料工具等,工具必须放在工具包里' } },
        { id: 5, hazardId: 3, controlMeasureId: 5, hazard: { id: 3, hazardName: '作业过程中工具脱手导致高处落物' }, controlMeasure: { id: 5, measureName: '不得跨站登高车和支撑结构之间' } },
        { id: 6, hazardId: 3, controlMeasureId: 6, hazard: { id: 3, hazardName: '作业过程中工具脱手导致高处落物' }, controlMeasure: { id: 6, measureName: '作业区域使用警示带进行隔离,无关人员禁止入内' } },
        { id: 7, hazardId: 4, controlMeasureId: 7, hazard: { id: 4, hazardName: '作业过程中突发身体不适或中暑' }, controlMeasure: { id: 7, measureName: '作业过程中合理安排休息时间,注意提醒作业人员饮水' } },
        { id: 8, hazardId: 4, controlMeasureId: 8, hazard: { id: 4, hazardName: '作业过程中突发身体不适或中暑' }, controlMeasure: { id: 8, measureName: '人员如有不适情况,立即停止作业,至阴凉通风处休息' } },
        { id: 9, hazardId: 5, controlMeasureId: 9, hazard: { id: 5, hazardName: '工具、物料、或墙上结构件受撞脱落' }, controlMeasure: { id: 9, measureName: '登高车下降前,梳理登高车平台上的物料和工具' } },
        { id: 10, hazardId: 5, controlMeasureId: 10, hazard: { id: 5, hazardName: '工具、物料、或墙上结构件受撞脱落' }, controlMeasure: { id: 10, measureName: '下降前,看护人员注意查看登高车附近的物料等' } }
      ],
      isActive: true,
      createTime: '2024-01-15 10:30:00',
      updateTime: '2024-01-15 10:30:00',
      creator: '系统管理员'
    },
    {
      id: 2,
      name: '电工作业模板',
      jobType: '电工作业',
      description: '适用于电气设备安装、维修、检修等作业',
      workSteps: [
        { id: 6, stepName: '作业前准备', sequence: 1, description: '检查电气设备和工具' },
        { id: 7, stepName: '电气作业', sequence: 2, description: '进行电气安装或维修' },
        { id: 8, stepName: '测试验收', sequence: 3, description: '测试电气系统功能' },
        { id: 9, stepName: '清理现场', sequence: 4, description: '清理作业现场' }
      ],
      hazards: [
        { id: 6, hazardName: '触电危险', description: '接触带电设备或线路导致触电', riskLevel: 'critical' },
        { id: 7, hazardName: '电弧烧伤', description: '电气短路产生电弧造成烧伤', riskLevel: 'high' },
        { id: 8, hazardName: '高处坠落', description: '在高处作业时可能坠落', riskLevel: 'high' },
        { id: 9, hazardName: '工具误用', description: '使用不合适的工具或方法', riskLevel: 'medium' }
      ],
      controlMeasures: [
        { id: 11, measureName: '停电验电挂牌', description: '停电后验电并悬挂警示牌', category: 'prevention' },
        { id: 12, measureName: '穿戴绝缘防护用品', description: '穿戴绝缘手套、绝缘鞋等防护用品', category: 'protection' },
        { id: 13, measureName: '使用绝缘工具', description: '使用经过检验的绝缘工具', category: 'protection' },
        { id: 14, measureName: '设置安全监护人', description: '设置专门的安全监护人', category: 'prevention' },
        { id: 15, measureName: '应急预案', description: '制定触电应急预案', category: 'emergency' }
      ],
      workStepHazards: [
        { id: 8, workStepId: 6, hazardId: 6, workStep: { id: 6, stepName: '作业前准备', sequence: 1 }, hazard: { id: 6, hazardName: '触电危险', riskLevel: 'critical' } },
        { id: 9, workStepId: 7, hazardId: 6, workStep: { id: 7, stepName: '电气作业', sequence: 2 }, hazard: { id: 6, hazardName: '触电危险', riskLevel: 'critical' } },
        { id: 10, workStepId: 7, hazardId: 7, workStep: { id: 7, stepName: '电气作业', sequence: 2 }, hazard: { id: 7, hazardName: '电弧烧伤', riskLevel: 'high' } },
        { id: 11, workStepId: 8, hazardId: 8, workStep: { id: 8, stepName: '测试验收', sequence: 3 }, hazard: { id: 8, hazardName: '高处坠落', riskLevel: 'high' } }
      ],
      hazardControls: [
        { id: 11, hazardId: 6, controlMeasureId: 11, hazard: { id: 6, hazardName: '触电危险', riskLevel: 'critical' }, controlMeasure: { id: 11, measureName: '停电验电挂牌', category: 'prevention' } },
        { id: 12, hazardId: 6, controlMeasureId: 12, hazard: { id: 6, hazardName: '触电危险', riskLevel: 'critical' }, controlMeasure: { id: 12, measureName: '穿戴绝缘防护用品', category: 'protection' } },
        { id: 13, hazardId: 7, controlMeasureId: 13, hazard: { id: 7, hazardName: '电弧烧伤', riskLevel: 'high' }, controlMeasure: { id: 13, measureName: '使用绝缘工具', category: 'protection' } },
        { id: 14, hazardId: 8, controlMeasureId: 14, hazard: { id: 8, hazardName: '高处坠落', riskLevel: 'high' }, controlMeasure: { id: 14, measureName: '设置安全监护人', category: 'prevention' } }
      ],
      isActive: true,
      createTime: '2024-01-16 14:20:00',
      updateTime: '2024-01-16 14:20:00',
      creator: '系统管理员'
    }
  ])

  const loading = ref(false)

  // 获取所有模板
  const getAllTemplates = () => {
    return templates.value
  }

  // 根据ID获取模板
  const getTemplateById = (id: number) => {
    return templates.value.find(template => template.id === id)
  }

  // 根据作业类型获取模板
  const getTemplatesByJobType = (jobType: string) => {
    return templates.value.filter(template => 
      template.jobType === jobType && template.isActive
    )
  }

  // 创建模板
  const createTemplate = (templateForm: JSATemplateForm) => {
    loading.value = true
    
    return new Promise<JSATemplate>((resolve) => {
      setTimeout(() => {
        const newId = Math.max(...templates.value.map(t => t.id)) + 1
        const now = new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-')

        // 生成关联关系
        const workSteps: JSAWorkStep[] = templateForm.workSteps.map((step, index) => ({
          id: newId * 100 + index + 1,
          ...step,
          sequence: index + 1
        }))

        const hazards: JSAHazard[] = templateForm.hazards.map((hazard, index) => ({
          id: newId * 1000 + index + 1,
          ...hazard
        }))

        const controlMeasures: JSAControlMeasure[] = templateForm.controlMeasures.map((measure, index) => ({
          id: newId * 10000 + index + 1,
          ...measure
        }))

        const workStepHazards = templateForm.workStepHazards.map((rel, index) => {
          const workStep = workSteps.find(ws => ws.sequence === rel.workStepSequence)
          const hazard = hazards.find(h => h.hazardName === rel.hazardName)
          return {
            id: newId * 100000 + index + 1,
            workStepId: workStep?.id || 0,
            hazardId: hazard?.id || 0,
            workStep: workStep!,
            hazard: hazard!
          }
        })

        const hazardControls = templateForm.hazardControls.map((rel, index) => {
          const hazard = hazards.find(h => h.hazardName === rel.hazardName)
          const controlMeasure = controlMeasures.find(cm => cm.measureName === rel.controlMeasureName)
          return {
            id: newId * 1000000 + index + 1,
            hazardId: hazard?.id || 0,
            controlMeasureId: controlMeasure?.id || 0,
            hazard: hazard!,
            controlMeasure: controlMeasure!
          }
        })

        const newTemplate: JSATemplate = {
          id: newId,
          ...templateForm,
          workSteps,
          hazards,
          controlMeasures,
          workStepHazards,
          hazardControls,
          isActive: true,
          createTime: now,
          updateTime: now,
          creator: '当前用户'
        }

        templates.value.push(newTemplate)
        loading.value = false
        resolve(newTemplate)
      }, 1000)
    })
  }

  // 更新模板
  const updateTemplate = (id: number, templateForm: JSATemplateForm) => {
    loading.value = true
    
    return new Promise<JSATemplate>((resolve) => {
      setTimeout(() => {
        const index = templates.value.findIndex(t => t.id === id)
        if (index === -1) {
          loading.value = false
          throw new Error('模板不存在')
        }

        const now = new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-')

        // 重新生成关联关系
        const workSteps: JSAWorkStep[] = templateForm.workSteps.map((step, idx) => ({
          id: id * 100 + idx + 1,
          ...step,
          sequence: idx + 1
        }))

        const hazards: JSAHazard[] = templateForm.hazards.map((hazard, idx) => ({
          id: id * 1000 + idx + 1,
          ...hazard
        }))

        const controlMeasures: JSAControlMeasure[] = templateForm.controlMeasures.map((measure, idx) => ({
          id: id * 10000 + idx + 1,
          ...measure
        }))

        const workStepHazards = templateForm.workStepHazards.map((rel, idx) => {
          const workStep = workSteps.find(ws => ws.sequence === rel.workStepSequence)
          const hazard = hazards.find(h => h.hazardName === rel.hazardName)
          return {
            id: id * 100000 + idx + 1,
            workStepId: workStep?.id || 0,
            hazardId: hazard?.id || 0,
            workStep: workStep!,
            hazard: hazard!
          }
        })

        const hazardControls = templateForm.hazardControls.map((rel, idx) => {
          const hazard = hazards.find(h => h.hazardName === rel.hazardName)
          const controlMeasure = controlMeasures.find(cm => cm.measureName === rel.controlMeasureName)
          return {
            id: id * 1000000 + idx + 1,
            hazardId: hazard?.id || 0,
            controlMeasureId: controlMeasure?.id || 0,
            hazard: hazard!,
            controlMeasure: controlMeasure!
          }
        })

        const updatedTemplate: JSATemplate = {
          ...templates.value[index],
          ...templateForm,
          workSteps,
          hazards,
          controlMeasures,
          workStepHazards,
          hazardControls,
          updateTime: now
        }

        templates.value[index] = updatedTemplate
        loading.value = false
        resolve(updatedTemplate)
      }, 1000)
    })
  }

  // 删除模板
  const deleteTemplate = (id: number) => {
    loading.value = true
    
    return new Promise<void>((resolve) => {
      setTimeout(() => {
        const index = templates.value.findIndex(t => t.id === id)
        if (index !== -1) {
          templates.value.splice(index, 1)
        }
        loading.value = false
        resolve()
      }, 500)
    })
  }

  // 获取作业类型列表
  const getJobTypes = computed(() => {
    const types = new Set(templates.value.map(t => t.jobType))
    return Array.from(types)
  })

  return {
    templates,
    loading,
    getAllTemplates,
    getTemplateById,
    getTemplatesByJobType,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    getJobTypes
  }
})
